package com.guoranhao.web.filter;

import com.guoranhao.tool.constants.CommonConstant;
import com.guoranhao.tool.utils.UUIDUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.core.annotation.Order;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;

/**
 * Description: TraceFilter
 * Copyright (c) Department of Research and Development/Beijing
 * All Rights Reserved.
 * @version 1.0 2018年07月04日 下午5:50 by 宫珣（gongxun@cloud-young.com）创建
 */
@WebFilter(urlPatterns = "/*")
@Order(2)
public class TraceFilter implements Filter {

    private static final Logger logger = LoggerFactory.getLogger(TraceFilter.class);

    @Override
    public void init(FilterConfig filterConfig) {
        logger.info("Init Trace filter...");
        // ...
        logger.info("Init Trace filter success!");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) {
        try {
            HttpServletRequest httpRequest = (HttpServletRequest) request;
            String gatewayTraceId = httpRequest.getHeader(CommonConstant.TRACE_ID_KEY.toLowerCase());
            MDC.put(CommonConstant.TRACE_ID_KEY, StringUtils.isBlank(gatewayTraceId) ? UUIDUtil.uuidCharUpper() : gatewayTraceId);
            //将请求和应答交给下一个处理器处理
            filterChain.doFilter(request, response);
        } catch (Exception e) {
            logger.error("TraceFilter error", e);
        } finally {
            MDC.remove(CommonConstant.TRACE_ID_KEY);
        }
    }

    @Override
    public void destroy() {
        logger.info("Destroy Trace filter success!");
    }
}
